package edu.fudan.lwang.worker;

import org.opencv.core.Mat;
import org.opencv.core.Scalar;

import edu.fudan.lwang.CodecHelper;
import edu.fudan.lwang.Common.CodecType;
import edu.fudan.lwang.callback.DecoderCallback;

public class DecoderWorker extends Thread {

	private String decoderId;
	private CodecType codecType;
	private DecoderCallback mDecoderCallback;
	private int frameWidth;
	private int frameHeight;
	private int frameType;
	
	public DecoderWorker(String decoderId, CodecType codecType, 
			int frameWidth, int frameHeight, int frameType, DecoderCallback mDecoderCallback) {
		this.decoderId = decoderId;
		this.codecType = codecType;
		this.frameWidth = frameWidth;
		this.frameHeight = frameHeight;
		this.frameType = frameType;
		this.mDecoderCallback = mDecoderCallback;
	}
	
	public int registerDecoder() {
		int codecTypeInt = CodecHelper.getInstance().getCodecTypeInt(codecType);
		return CodecHelper.getInstance().registerDecoder(decoderId, codecTypeInt);
	}
	
	public void releaseDecoder() {
		CodecHelper.getInstance().releaseDecoder(decoderId);
	}
	
	@Override
	public void run() {
		
		int[] results = new int[2];
		Mat yuvMat = new Mat(frameHeight, frameWidth, frameType, new Scalar(0));
		
		while(!Thread.interrupted()) {
			byte[] encodedData = mDecoderCallback.getEncodedData();
			if(encodedData != null) {
				CodecHelper.getInstance()
						.decodeFrame(decoderId, encodedData, results, yuvMat.nativeObj);
				if(results[0] != 0) {
					mDecoderCallback.onDataDecoded(yuvMat, results[1]);
				}
			}
		}
	}
}
